package com.leet.tree;

import java.util.LinkedList;
import java.util.Queue;

public class IsSubtree {
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        boolean flag = false;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            int size = q.size();
            for(int i = 0; i < size; i++){
                TreeNode front = q.poll();
                flag = helper(front,subRoot);
                if(flag) return true;
                if(front.left != null) q.offer(front.left);
                if(front.right != null) q.offer(front.right);
            }
        }
        return false;
    }
    public boolean helper(TreeNode root, TreeNode subRoot){
        if(root == null && subRoot == null) return true;
        if(root == null && subRoot != null) return false;
        if(root != null && subRoot == null) return false;
        return root.val == subRoot.val && helper(root.left,subRoot.left)
                && helper(root.right,subRoot.right);

    }
}
